package com.baosight.sczx.zm.ce.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.ce.Equipment;
import com.baosight.sczx.common.zm.cInterface.ce.StandardEquipment;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCE;
import com.baosight.sczx.zm.ce.domain.ZMCEEquipmentClass;

/**
 * <p>Title: ServiceZMCE91.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张志芳
 * @version 1.0
 * <pre>Histroy:
 *          2011-12-15 上午11:37:48  张志芳  Create
 *</pre>
 */
public class ServiceZMCE91 extends ServiceEPBase {

	/**
	 * 初始化
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCE91</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-15下午02:37:59 张志芳
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {		
		String isLeaf = inInfo.getString("isLeaf");//判断是否为叶子
		
		//非叶子节点
		if(isLeaf != null && "0".equals(isLeaf)){
			inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的			
			EiInfo outInfo = this.query(inInfo);
			return outInfo;				
		}
		//叶子节点	
		else{
			String fdParentId = inInfo.getString("fdParentId");
			StaticTools.setQueryParameters(inInfo, "fdKeyId", fdParentId, true);			
			EiInfo outInfo = super.query(inInfo, "ZMCEEquipmentClass.query", new ZMCEEquipmentClass());
			return outInfo;
		}				
	}

	
	/**
	* 查询
	* <p>Function: ConnectStr</p>
	* <p>Description: </p>
	* <p>return value:String</p>
	* <p>throws Exception:</p>
	* <p>History:
	*    2011-12-15下午02:38:16 张志芳
	* </p>
	*
	*/
	@Override
	public EiInfo query(EiInfo inInfo) {		
		String fdParentId = inInfo.getString("fdParentId");
		StaticTools.setQueryParameters(inInfo, "fdParentId", fdParentId, true);//添加查询条件
		String fdToencode = inInfo.getString("fdToencode");
		StaticTools.setQueryParameters(inInfo, "fdToencode", fdToencode, true);//添加查询条件
		EiInfo outInfo = super.query(inInfo, "ZMCEEquipmentClass.query", new ZMCEEquipmentClass());				
		return outInfo;
	}
	
	/**新增
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCE02</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-15下午02:38:16 张志芳
	 * </p>
	 *
	*/
	@Override
	public EiInfo insert(EiInfo inInfo) {
		//判断级别数
		if(checkLevel(inInfo.getBlock("result").getCellStr(0, "fdParentId"))>=SystemSettingCE.getInstance().getClassLevel())
		{
			inInfo.setStatus(-1);
			inInfo.setMsg("超过基础设置中分类级数，该父分类下不能新增下级类别");
			return inInfo;
		}
		
		boolean isNoRepeat = validate(inInfo, "ZMCEEquipmentClass.validate", new HashMap<String, String>());		
		
		if(isNoRepeat) {
			return inInfo;
		}
		else {
			String str = ConnectStr(inInfo.getBlock("result").getCell(0, "fdParentToencode" ).toString(),inInfo.getBlock("result").getCell(0, "fdSuffix" ).toString());//拼接传参
			inInfo.getBlock("result").setCell(0, "fdToencode", str);//赋值
			inInfo.getBlock("result").setCell(0, "fdCode", str.substring(2));//赋值
			inInfo.getBlock("result").setCell(0, "fdKeyId", TablePk.getInstance().getNextValue("T_CE_EQUIPMENTCLASS"));//主键
			EiInfo outInfo = super.insert(inInfo, "ZMCEEquipmentClass.insert", "result");
			return outInfo;
		}
	}
	
	/**修改
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCE02</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-15下午02:38:16 张志芳
	 * </p>
	 *
	*/
	@Override
	public EiInfo update(EiInfo inInfo) {
		//校验编号或名称是否重复
		Map<String, String> params = new HashMap<String, String>();
		params.put("fdKeyId", inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
		
		boolean isNoRepeat = validate(inInfo, "ZMCEEquipmentClass.validate", params);
		
		
		if(isNoRepeat) {
			return inInfo;
		}
		//校验分类下是否有子分类
		if(inInfo.getBlock("result").getCellStr(0, "fdIsLeaf").equals("1")){
			boolean hasChild = hasChildren(inInfo, "ZMCEEquipmentClass.hasChildren", params);
			if(hasChild) {
				return inInfo;
			}
		}

		String str = ConnectStr(inInfo.getBlock("result").getCell(0, "fdParentToencode" ).toString(),inInfo.getBlock("result").getCell(0, "fdSuffix" ).toString());//拼接传参
		inInfo.getBlock("result").setCell(0, "fdToencode", str);//赋值	
		inInfo.getBlock("result").setCell(0, "fdCode", str.substring(2));//赋值
		EiInfo outInfo = super.update(inInfo, "ZMCEEquipmentClass.update");
		return outInfo;
		
		
	}

	/**删除
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCE02</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-15下午02:38:16 张志芳
	 * </p>
	 *
	*/
	@Override
	public EiInfo delete(EiInfo inInfo) {
        EiInfo outInfo = null;
		
        //有无子模块校验
		boolean validateValue = hasChildrenModule(inInfo, "ZMCEEquipmentClass.validateHasChildren");
		if(validateValue) {
			return inInfo;
		}
		
		//判断是否有设备
		validateValue = hasEquipment(inInfo);
		if(validateValue) {
			return inInfo;
		}
		
		EiInfo _temp = super.delete(inInfo, "ZMCEEquipmentClass.delete");//执行删除
		outInfo = query(inInfo);
        outInfo.setMsg(_temp.getMsg());
        outInfo.setDetailMsg(_temp.getDetailMsg());
		return outInfo;
		
	}


	
	
	/**
	 * 编号重复验证
	 * <p>Function: validateNo</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-15下午02:38:16 张志芳
	 * </p>
	 *
	 */

	@SuppressWarnings("unchecked")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		params.put("fdCode", inInfo.getBlock("result").getCellStr(0, "fdCode"));
		params.put("fdName", inInfo.getBlock("result").getCellStr(0, "fdName"));
		params.put("fdParentId", inInfo.getBlock("result").getCellStr(0, "fdParentId"));
		
		List<ZMCEEquipmentClass> result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setStatus(-1);	
			String msg="";
			if(result.size()==1)
			{				
				if(result.get(0).getFdCode().equals(inInfo.getBlock("result").getCellStr(0, "fdCode")))
				{			
					msg += "编号必须唯一！";					
				}
				if(result.get(0).getFdName().equals(inInfo.getBlock("result").getCellStr(0, "fdName")))
				{
					msg += "类别名称有重复！";	
				}
			}
			else
			{
				msg += "编号必须唯一，类别名称有重复！";
			}
			inInfo.setMsg(msg);
			return true;
		}
		return false;
	}
	
	/**
	 * 验证分类下是否有子分类
	 * <p>Function: hasChildren</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-02-06下午02:38:16 高强
	 * </p>
	 *
	 */

	@SuppressWarnings("unchecked")
	private boolean hasChildren(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		List<ZMCEEquipmentClass> result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setStatus(-1);	
			String msg="该分类已经存在子类别不能更新!";
			inInfo.setMsg(msg);
			return true;
		}
		return false;
	}
	
	/**
	 * 判断模块下是否有子模块
	 * <p>Function: hasChildrenModule</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-15下午02:38:16 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean hasChildrenModule(EiInfo inInfo, String sqlName) {
		List<String> _list = new ArrayList<String>();
		Map<String,List<String>> params = new HashMap<String,List<String>>();
		for(int i = 0; i < inInfo.getBlock(EiConstant.resultBlock).getRowCount(); i++){
			_list.add(inInfo.getBlock("result").getCellStr(i, "fdKeyId"));
		}
		params.put("fdKeyIds", _list);
		List result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setStatus(-1);
			inInfo.setMsg("所选设备分类下有子分类，不能删除！");
			return true;
		}
		return false;
	}
	
	/**
	 * 判断模块下是否有设备存在
	 * <p>Function: hasChildrenModule</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-15下午02:38:16 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean hasEquipment(EiInfo inInfo) {
		for(int i=0;i<inInfo.getBlock("result").getRowCount();i++)
		{
			if(Equipment.hasEquipment(inInfo.getBlock("result").getCellStr(i, "fdKeyId"))||
			   StandardEquipment.hasEquipment(inInfo.getBlock("result").getCellStr(i, "fdKeyId"))) {
				inInfo.setStatus(-1);
				inInfo.setMsg("所选设备分类下有设备存在，不能删除！");				
				return true;
			}			
		}
		return false;
	}
	
	/**
	 * 获得某目录的级数
	 * <p>Function: checkLevel</p>
	 * <p>Description: </p>
	 * <p>return value:long</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-3-6上午08:49:57 张志芳
	 * </p>
	 *
	 */
	private long checkLevel(String parentId)
	{
		long result=1;
		Map map=new HashMap();
		map.put("fdKeyId", parentId);
		List<ZMCEEquipmentClass> list=dao.query("ZMCEEquipmentClass.query",map);
		if(list.size()>0)
		{
			while(!list.get(0).getFdParentId().equals("root0") && result<SystemSettingCE.getInstance().getClassLevel())
			{
				result++;
				map.put("fdKeyId", list.get(0).getFdParentId());
				list=dao.query("ZMCEEquipmentClass.query",map);
			}
		}
		return result;
	}

	/**
	 * 内码拼接
	 * <p>Function: ConnectStr</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-15下午02:38:16 张志芳
	 * </p>
	 *
	 */
	 public String ConnectStr(String str1, String str2){
		StringBuffer fdToencode=new StringBuffer();
		fdToencode.append(str1).append(str2);
		return fdToencode.toString();
		  
	 }
	 	 
}
